/*
 * @lc app=leetcode.cn id=208 lang=java
 *
 * [208] 实现 Trie (前缀树)
 */

// @lc code=start
class Trie {
    private class TrieNode{
        boolean isEnd;
        TrieNode[] next;
        TrieNode(){
            this.isEnd = false;
            this.next = new TrieNode[26];
        }
    }
    TrieNode root;
    /** Initialize your data structure here. */
    public Trie() {
        root = new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        //从根节点每个字符插入
        TrieNode cur = root;
        for(char s : word.toCharArray()){
            int ch = s-'a';
            if(cur.next[ch]==null){//如果那个字母没出现过。
                cur.next[ch]=new TrieNode();
            }
            cur = cur.next[ch];
        }
        cur.isEnd=true;//访问到最后了
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        //搜索到之后要看isEnd为true
        TrieNode cur = root;
        for(char s : word.toCharArray()){
            int ch = s-'a';
            if(cur.next[ch]==null){//说明这个字符不存在
                return false;
            }
            cur = cur.next[ch];
        }
        return cur.isEnd;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode cur = root;
        for(char s : word.toCharArray()){
            int ch = s-'a';
            if(cur.next[ch]==null){//说明这个字符不存在
                return false;
            }
            cur = cur.next[ch];
        }
        return true;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */
// @lc code=end

